package com.sptpc.exam;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 检查验证码
        String code = request.getParameter("verify");
        // 生成验证码后，kaptcha会把验证码写入session中以KAPTCHA_SESSION_KEY为名字保存
        String verifyCode = (String) request.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        if (code!=null &&code.equals(verifyCode)) {
            // 1.1 成功
            // 2. 检查用户名和密码
            String su =request.getParameter("su");
            String name = request.getParameter("name");
            String password = request.getParameter("password");

            if (su.equals("student")){
                if (name.equals("test") && password.equals("123456")) {
                    // 2.1 学生成功页面
                    request.getSession().setAttribute("username", "罗尧");
                    request.getRequestDispatcher("success.jsp").forward(request,response);
                }else {// 2.1 返回登录，并给出错误信息
                    request.setAttribute("errorMsg", "用户名或密码错误或者该学生账号不存在");
                    request.getRequestDispatcher("index.jsp").forward(request,response);
                }
            }else if(su.equals("teacher")){
                if(name.equals("teacher") && password.equals("123456")) {
                    // 2.1 老师成功页面
                    request.getSession().setAttribute("username", "教师");
                    request.getRequestDispatcher("admin.jsp").forward(request,response);
                }else {// 2.1 返回登录，并给出错误信息
                    request.setAttribute("errorMsg", "用户名或密码错误或者该老师账号不存在");
                    request.getRequestDispatcher("index.jsp").forward(request,response);
                }
            }




        } else { // 1.2 返回登录，并给出错误信息
            request.setAttribute("errorMsg", "验证码错误");
            request.getRequestDispatcher("index.jsp").forward(request,response);

        }
    }
}
